<template>
  <UtilForm ref="userFormRef" :labels="state.labels" :form-data="state.form" :config="formconfig"
    @emit-util-form="emitUtilFormHandler">
    <el-button @click="handleCloseDialog">取消</el-button>
    <el-button type="success" @click="putUserHandler">保存</el-button>
  </UtilForm>
</template>

<script setup>
import UtilForm from '../../components/UtilForm.vue';
import { ref, reactive, watch, getCurrentInstance, computed } from 'vue';
import { useStore } from 'vuex';
import { ElMessage } from 'element-plus';

const store = useStore();
const { proxy: { $axios, $utils } } = getCurrentInstance();
const emit = defineEmits(['emit-change-user']);
const storeUser = computed(() => store.getters['user/getUser']);

const props = defineProps({
  status: Boolean,
  formData: {
    type: Object,
    required: true,
    default: () => ({})
  }
});

const formconfig = reactive({
  reset: true,
  clearable: false
});

const userFormRef = ref();
const state = reactive({
  form: {},
  labels: [
    { field: 'id', label: 'ID', labelType: 'text', disabled: true },
    { field: 'username', label: '用户名', labelType: 'text', disabled: true },
    { field: 'fullname', label: '姓名', labelType: 'text', required: true },
    {
      field: 'gender',
      label: '性别',
      labelType: 'radio',
      required: true,
      dict: getEnumAllMembers('gender')
    },
    {
      field: 'role',
      label: '角色',
      labelType: 'checkbox',
      required: true,
      dict: getEnumAllMembers('role')
    },
    { field: 'age', label: '年龄', labelType: 'inputNumber', min: 0, max: 122, required: true },
    // {
    //   field: 'avatar',
    //   label: '头像',
    //   labelType: 'upload',
    //   action: '/api/user/addAvatar',
    //   limit: 1
    // },
  ]
});

function getEnumAllMembers(key) {
  const statusDef = store.getters['enums/getEnums'](key);
  return statusDef.getAllMembers()
}

function handleCloseDialog(refresh = false) {
  formconfig.clearable = true;
  emit('emit-change-user', { status: false, refresh });
}

function emitUtilFormHandler(data) {
  state.form = data.form;
}

async function putUserHandler() {
  const params = formaterParams(state.form);
  const path = '/api/user/update/' + params.id;

  try {
    const { code, data, message } = await $axios.put(path, params);

    if (code === 200) {
      const currentIsAuthor = $utils.isValidValue(data) && data.id === storeUser.value.id;
      if (currentIsAuthor) {
        store.commit('user/setUser', data);
      }
      ElMessage.success(message || '用户信息修改成功');
      setTimeout(() => handleCloseDialog(), 1000);
    }
  } catch (err) {
    console.warn('用户信息修改失败', err);
  }
}


function formaterParams(data) {
  let role = 0;
  const roles = data.role || [];

  if (roles.length) {
    role = roles.reduce((t, c) => t | c);
  }
  return { ...data, role };
}

watch(() => props.formData, val => {
  Object.entries(val).forEach(([key, value]) => {
    if (key === 'role') {
      const enumDef = store.getters['enums/getEnums']('role') || {};
      const members = enumDef.getAllMembers() || [];
      const roleValue = members
        .filter(m => (parseInt(value) & m.value) === m.value)
        .map(m => m.value);

      state.form[key] = roleValue || [];
    } else {
      state.form[key] = value;
    }
  });
}, { immediate: true, deep: true });

watch(() => props.status, s => {
  formconfig.clearable = s;
});
</script>

<style scoped>
.custom-label {
  width: 120px;
  text-align: right;
}

:deep(.el-descriptions__cell) {
  display: flex;
}

/* :deep(tr:last-child .el-descriptions__cell) {
  display: flex;
  padding-left: 120px;
} */
</style>